package zyq.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import zyq.dao.UserDaoImpl;
import zyq.po.Student;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet  extends HttpServlet {
    // 响应客户端请求的方法
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {

        String errMsg = "";
        // Servlet本身并不输出响应到客户端，因此必须将请求转发到视图页面
        // 获取请求参数
        String username = request.getParameter("username");
        String pass = request.getParameter("pass");
        try {
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            Student stu = new Student();
            stu.setStuName(username);
            stu.setStuPwd(pass);

            UserDaoImpl userDao = (UserDaoImpl) ac.getBean("userDaoImpl");

            boolean result = userDao.login(stu);

            if (result==true) {
                // 获取session对象
                HttpSession session = request.getSession(true);
                // 设置session属性，跟踪用户会话状态
                session.setAttribute("name", username);
                // 获取转发对象
                RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
                // 转发请求
                rd.forward(request, response);
            } else {
                // 用户名和密码不匹配时
                errMsg += "您输入的用户名或密码错误,请重新输入";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果出错，转发到重新登录
        if (errMsg != null && !errMsg.equals("")) {
            RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
            request.setAttribute("err", errMsg);
            rd.forward(request, response);
        }
    }
}